package com.heima.kafka.simple;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 生产者快速入门
 */
public class ProducerStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //2.设置连接信息
        Properties properties = new Properties();
             //指定kafka的链接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.35.135:9092");
        //设置发送消息的key和value均进行序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"gzip");
        //1.创建生产者对象
        KafkaProducer<String,String> kafkaProducer = new KafkaProducer<String, String>(properties);

        /**
         * 3.发送消息队列
         * ProducerRecord(String topic,K key,V value)
         * 参数1表示发送消息的主题
         * 参数2表示消息的key   一定要是字符串类型
         * 参数3表示消息的内容   一定要是字符串类型
         */
        ProducerRecord<String, String> record = new ProducerRecord<>("simple_topic","key001","hello kafka");
        /*Future<RecordMetadata> future = kafkaProducer.send(record);
        RecordMetadata recordMetadata = future.get();
        System.out.println(recordMetadata.offset());*/
        kafkaProducer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                //如果发生异常的话可以执行我们的重试机制
                if (e!=null){
                    //则执行重试机制
                    System.out.println("发生异常了"+e.getMessage());
                }
            }
        });


        /**
         * 关闭消息
         * 注意,一定要关闭,否则消息没有发送成功
         */
        kafkaProducer.close();
    }
}
